#include "history.h"

History* History::_instance = NULL;

History::History()
{
    _stack = new QList<Command*>();
    _stackPtr = _stack->begin();
}

History* History::instance(){
    if(_instance == NULL)
        _instance = new History();

    return _instance;
}

void History::push(Command *command){
    //Clear everything after the inserted command
    _stack->erase(_stackPtr, _stack->end());
    //Insert at the new end of the stack and
    //reset the stack pointer
    _stackPtr = _stack->insert(_stackPtr, command);
    _stackPtr++;

    QLog::log(QString("Do: ") + command->historyTip());

    emitStatus();
}

void History::clear(){
    _stack->clear();
    _stackPtr = _stack->begin();

    emitStatus();
}

void History::undo(){
    //The stack pointer always points one
    //after the top of the stack
    if(_stackPtr != _stack->begin()){
        _stackPtr--;
        (*_stackPtr)->undo();

        QLog::log(QString("Undo: ") + (*_stackPtr)->historyTip());
    }

    emitStatus();
}

void History::redo(){
    if(_stackPtr != _stack->end()){
        (*_stackPtr)->execute();

        QLog::log(QString("Redo: ") + (*_stackPtr)->historyTip());

        _stackPtr++;
    }

    emitStatus();
}

void History::emitStatus(){
    bool undoStatus = (_stackPtr == _stack->begin()) ? false : true;
    bool redoStatus = (_stackPtr == _stack->end()) ? false : true;
    QString undoTip = tr("Undo "), redoTip = tr("Redo ");

    if(undoStatus){
        undoTip += (*(_stackPtr - 1))->historyTip();
    }
    if(redoStatus){
        redoTip += (*_stackPtr)->historyTip();
    }

    emit status(undoStatus, redoStatus, undoTip, redoTip);
}
